//
//  KVEmoticonModelManeger.swift
//  KVEmoticon
//
//  Created by 李康卫 on 16/7/29.
//  Copyright © 2016年 李康卫. All rights reserved.
//

import UIKit

class KVEmoticonModelManeger: NSObject {
    ///表情包管理者
      static let sharedEmoticonManeger = KVEmoticonModelManeger()
    ///表情包目录
    let packagePath = NSBundle.mainBundle().pathForResource("Emoticons.bundle", ofType: nil)
    ///所有表情包
    lazy var emoticonPackages:[KVEmoticonPackgeModel] = self.loadPackages()
    ///加载所有表情包
    func loadPackages() -> [KVEmoticonPackgeModel]{
        
        //获取沙盒数据
        let emoticonsModel = readDataFormFile()
        let recent = KVEmoticonPackgeModel(id: "", group_name_cn: "最近", emoticons: emoticonsModel)
        
        let sinaDefault = loadPackage("com.sina.default")
        
        let emoji = loadPackage("com.apple.emoji")

        let lxh = loadPackage("com.sina.lxh")
        
        return [recent,sinaDefault,emoji,lxh]
    }
    
    ///加载单个表情包
    private func loadPackage(id: String) -> KVEmoticonPackgeModel {
        //表情包路径拼接
        let infoPath = packagePath! + "/\(id)" + "/info.plist"
        //加在info。plist的字典
        let infoDic = NSDictionary(contentsOfFile: infoPath)
        //取出字典给模型赋值
        let id = infoDic!["id"] as! String
        let group_name_cn = infoDic!["group_name_cn"] as! String
        let emoticonsArr = infoDic!["emoticons"] as! [[String: String]]
        var emoticons = [KVEmoticonModel]()
        for emoticonDic in emoticonsArr {
            let emoticon = KVEmoticonModel(id: id,dic: emoticonDic)
            emoticons.append(emoticon)
        }
        return KVEmoticonPackgeModel(id: id, group_name_cn: group_name_cn, emoticons: emoticons)
    }
    
    ///添加最近表情包
    func addRecentEmoticon(emoticon: KVEmoticonModel) {
        //获取第一组第一个元素进行赋值
           var emoticons = emoticonPackages[0].emoticonsOfPage[0]
        
        //遍历相同则删除后面的一个
        for (index,lastEmoticon) in emoticons.enumerate() {
            if emoticon == lastEmoticon {
                emoticons.removeAtIndex(index)
            }
        }
        emoticons.insert(emoticon, atIndex: 0)
        
        //大于20删除
        if emoticons.count > 20 {
            emoticons.removeLast()
        }
        //归档解档
        saveDateToFlie(emoticons)
        print("emoticonsCount:\(emoticons.count)")

        // 重新赋值回去
        emoticonPackages[0].emoticonsOfPage[0] = emoticons
    }

    //save归档p
    private func saveDateToFlie(emoticons: [KVEmoticonModel]) {

        //保存的路径 
        // MARK: - 注意：图片保存的是bundle路径每次都是会变化的要重新拼接路径
        let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
        let filePath = documentPath! + "/" + "emoticon.plist"
        NSKeyedArchiver.archiveRootObject(emoticons, toFile: filePath)
    }
    
    ///读取沙盒数据、
    private func readDataFormFile() -> [KVEmoticonModel] {
        let documentPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last
        let filePath = documentPath! + "/" + "emoticon.plist"
        let emoticons = NSKeyedUnarchiver.unarchiveObjectWithFile(filePath) as? [KVEmoticonModel]
        return emoticons ?? [KVEmoticonModel]()
    }
}
